//
//  CardRecordViewController.m
//  MRBang
//
//  Created by 铅笔 on 16/4/20.
//  Copyright © 2016年 杭州易网新科技. All rights reserved.
//

#import "CardRecordViewController.h"

#import "CardRecordCell.h"

#import "CardRecordModel.h"

#define CELLHEIGHT 188*PROPORTION_WIDTH


static int from =0;
static int to=20;

@interface CardRecordViewController ()<UITableViewDataSource,UITableViewDelegate>
{}
@property (nonatomic,strong) UITableView *tableView_CardRecord;

@property (nonatomic,strong) NSMutableArray *mutableArray_cardRecord;

@end

@implementation CardRecordViewController

/**
 *数据的懒加载
 */
- (NSMutableArray *) mutableArray_cardRecord
{
    if (_mutableArray_cardRecord==nil) {
        _mutableArray_cardRecord = [[NSMutableArray alloc] init];
    }
    return _mutableArray_cardRecord;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"办卡记录";
    
    self.view.backgroundColor = COLOR_EVERYVIEWBG;
    
    [self initWithCardRecordSubviews];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    //网络数据请求
    [self DataSourceRequestCardRecordView];

}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = YES;
    
    [self.mutableArray_cardRecord removeAllObjects];
}

#pragma mark --- 创建 视图布局界面
- (void) initWithCardRecordSubviews
{
    self.tableView_CardRecord = [[UITableView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight+64)];
    [self.view addSubview:self.tableView_CardRecord];
    self.tableView_CardRecord.dataSource = self;
    self.tableView_CardRecord.delegate = self;
    self.tableView_CardRecord.showsVerticalScrollIndicator = NO;
    self.tableView_CardRecord.separatorStyle =UITableViewCellSeparatorStyleNone;
    self.tableView_CardRecord.backgroundColor = COLOR_EVERYVIEWBG;
    
    [self setUprefresh];
    [self setTopRefresh];
}

#pragma mark - 集成下拉刷洗 上拉加载
- (void)setUprefresh
{
    __weak __typeof(self) weakSelf = self;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView_CardRecord.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadNewData];
    }];
    
    // 马上进入刷新状态
    //    [self.tableView.header beginRefreshing];
}

- (void)setTopRefresh
{
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [footer setTitle:@"暂无更多记录!" forState:MJRefreshStateNoMoreData];
    // 设置footer
    self.tableView_CardRecord.footer = footer;
}

#pragma mark - 数据处理相关
#pragma mark 下拉刷新数据
- (void)loadNewData
{
    from=0;
    
    [self.mutableArray_cardRecord removeAllObjects];
    
    [self DataSourceRequestCardRecordView];
    
    // 拿到当前的下拉刷新控件，结束刷新状态
    [self.tableView_CardRecord.header endRefreshing];
    
}

#pragma mark 上拉加载更多数据
- (void)loadMoreData
{
    from+=20;
    [self DataSourceRequestCardRecordView];
    
}

#pragma mark --- UITableViewDataSource
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.mutableArray_cardRecord.count;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     static NSString *cellCardRecordID = @"cellCardRecordID";
    
    CardRecordCell *cell_cellCardRecord = [tableView dequeueReusableCellWithIdentifier:cellCardRecordID];
    if (cell_cellCardRecord == nil) {
        cell_cellCardRecord = [[CardRecordCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellCardRecordID];
    }
    
    UIView *view_line = [[UIView alloc] initWithFrame:CGRectMake(27*PROPORTION_WIDTH, CELLHEIGHT-1, kScreenWidth, 1.0)];
    [cell_cellCardRecord.contentView addSubview:view_line];
    view_line.backgroundColor = [BaseViewController colorWithHexString:@"#EEEFF1"];

     cell_cellCardRecord.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.mutableArray_cardRecord.count!=0) {
        [cell_cellCardRecord initWithCarRecordModel:self.mutableArray_cardRecord[indexPath.row]];
    }
    return cell_cellCardRecord;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CELLHEIGHT;
}

#pragma mark -- 网络数据请求
- (void) DataSourceRequestCardRecordView
{
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    
    if (![UIView NetFromStatus:status]) {
        NSLog(@"没有网络");
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [UIView showAlertMsg:@"网络连接已断开" andShowBgColor:[UIColor blackColor] andLabelTectColor:[UIColor whiteColor]];
        
        return;
    }
    else
    {
        NSString *strUrl = [NSString stringWithFormat:@"%@creditcard/get",MRAPI];

        NSDictionary *paras_bankList = @{@"memberid":[[NSUserDefaults standardUserDefaults] objectForKey:@"memberid"],@"from":[NSNumber numberWithInt:from],@"to":[NSNumber numberWithInt:to]};

        [[HttpRequest shardWebUtil] getNetworkRequestURLString:strUrl parameters:paras_bankList success:^(id obj) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

            NSLog(@"creditcard/get%@",obj);
            NSString *str_false = obj[@"error"];

            if (str_false.length==0) {
                NSArray *array_data = obj[@"data"];
                 _dataCount=[obj[@"count"] intValue];
                
                if (array_data.count!=0) {
                    for (int i=0; i<array_data.count; i++) {
                        CardRecordModel *model = [[CardRecordModel alloc] init];
                        [model decodeDic:array_data[i]];
                        [self.mutableArray_cardRecord addObject:model];
                    }
                }
                else
                {
                    [BaseViewController showMessage:@"暂无数据"];
                    
                }

                [self.tableView_CardRecord reloadData];
                
                
                if (self.mutableArray_cardRecord.count == _dataCount) {
                    // 拿到当前的上拉刷新控件，变为没有更多数据的状态
                    [self.tableView_CardRecord.footer noticeNoMoreData];
                }
                else
                {
                    // 拿到当前的上拉刷新控件，结束刷新状态
                    [self.tableView_CardRecord.footer endRefreshing];
                }

            }
            else
            {
                [BaseViewController showMessage:str_false];
            }

        } fail:^(NSError *error) {
            [BaseViewController showMessage:@"请求超时"];
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}


@end
